<template>
  <div style="padding: 20px;">
    <div class="crumbs">
      <div class="container">
        <h3>商品介绍</h3>
        <el-form ref="query.goods" :model="query.goods" label-width="70px" :rules="rules">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="商品ID" label-width="150px" prop="id">
                <el-input v-model="query.goods.id" size="mini" clearable :disabled="true" />
              </el-form-item>
              <el-form-item label="商品名称" label-width="150px" prop="name">
                <el-input v-model="query.goods.name" size="mini" clearable />
              </el-form-item>
              <el-form-item label="商品编号" label-width="150px">
                <el-input v-model="query.goods.goodsSn" size="mini" clearable />
              </el-form-item>
              <el-form-item label="市场售价" label-width="150px">
                <el-input v-model="query.goods.counterPrice" placeholder="请输入内容">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="是否新品" label-width="150px">
                <template v-slot="scope">
                  <el-radio v-model="query.goods.isNew" :label="true">新品</el-radio>
                  <el-radio v-model="query.goods.isNew" :label="false">非新品</el-radio>
                </template>
              </el-form-item>
              <el-form-item label="是否热卖" label-width="150px">
                <template>
                  <el-radio v-model="query.goods.isHot" :label="false">普通</el-radio>
                  <el-radio v-model="query.goods.isHot" :label="true">热卖</el-radio>
                </template>
              </el-form-item>
              <el-form-item label="是否在售" label-width="150px">
                <template>
                  <el-radio v-model="query.goods.isOnSale" :label="true">在售</el-radio>
                  <el-radio v-model="query.goods.isOnSale" :label="false">未售</el-radio>
                </template>
              </el-form-item>
              <el-form-item label="商家图片" label-width="150px">
                <el-upload class="avatar-uploader" :headers="headers"
                  action="http://admin.bsmall.byesame.com/admin/storage/create" :show-file-list="false"
                  :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                  <img v-if="query.goods.picUrl" :src="query.goods.picUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </el-form-item>
              <el-form-item label="宣传画廊" label-width="150px">
                <el-upload v-model="query.goods.gallery" :headers="headers"
                  action="http://admin.bsmall.byesame.com/admin/storage/create" list-type="picture-card"
                  :on-remove="handleRemove" :limit="5" :show-file-list="true" :file-list="query.goods.gallery"
                  :on-progress="handleProgress" :on-success="handleSuccess">
                  <i class="el-icon-plus" />
                </el-upload>
              </el-form-item>
              <el-form-item label="商品单位" label-width="150px">
                <el-input v-model="query.goods.unit" size="mini" clearable placeholder="件/个/盒" />
              </el-form-item>
              <el-form-item label="关键字" label-width="150px">
                <el-tag v-for="tag in dynamicTags" :key="tag" closable :disable-transitions="false"
                  @close="handleClose(tag)">
                  {{ tag }}
                </el-tag>
                <el-input v-if="inputVisible" ref="saveTagInput" v-model="inputValue" class="input-new-tag" size="mini"
                  @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm" />
                <el-button v-else class="button-new-tag" type="primary" size="mini" icon="el-icon-plus"
                  @click="showInput">增加</el-button>
              </el-form-item>
              <el-form-item label="所属分类" label-width="150px">
                <el-cascader v-model="query.goods.categoryId" clearable :options="categoryList"
                  :props="{ expandTrigger: 'hover' }" @change="handleChange" />
              </el-form-item>
              <el-form-item label="所属品牌商" label-width="150px">
                <el-select v-model="query.goods.brandId" clearable placeholder="请选择" @change="handle">
                  <el-option v-for="item in brandList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="商品简介" label-width="150px">
                <el-input v-model="query.goods.brief" size="mini" clearable />
              </el-form-item>
              <el-form-item label="商品详细介绍" label-width="150px">
                <editor v-model="query.goods.detail" :init="editorInit" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="crumbs">
      <div class="container">
        <h3>商品规格</h3>
        <div class="tables">
          <el-table :data="query.specifications" style="width: 100%">
            <el-table-column prop="specification" label="规格名" width="401" />
            <el-table-column prop="value" label="规格值" width="399">
              <template v-slot="scope">
                <el-tag>{{ scope.row.value }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="picUrl" label="规格图片" width="399">
              <template v-slot="scope">
                <img v-if="scope.row.picUrl" :src="scope.row.picUrl" alt="" style=" height: 40px; width: 40px;"></img>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button size="mini" type="primary" @click="install(scope.row)">设置</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div class="dialogDiv">
      <el-dialog :title="title" :visible.sync="dialogFormVisible">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" style="width: 400px;margin-left: 50px;">
          <el-form-item label="规格名" label-width="100px" prop="specification">
            <el-input v-model="ruleForm.specification" style="width: 280px;" clearable disabled />
          </el-form-item>
          <el-form-item label="规格值" label-width="100px" prop="value">
            <el-input v-model="ruleForm.value" style="width: 280px;" clearable disabled />
          </el-form-item>
          <el-form-item label="规格图片" label-width="100px" prop="picUrl">
            <el-upload class="avatar-uploader" :headers="headers"
              action="http://admin.bsmall.byesame.com/admin/storage/create" :show-file-list="false"
              :on-success="handleAvata" :before-upload="beforeAvatarUpload">
              <img v-if="ruleForm.picUrl" :src="ruleForm.picUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="crumbs">
      <div class="container">
        <h3>商品库存</h3>
        <div class="tables">
          <el-table :data="query.products" style="width: 100%">
            <el-table-column prop="specification" label="货品规格" width="302">
              <template v-slot="scope">
                <el-tag>{{ scope.row.specifications[0] }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="货品价值" width="299" />
            <el-table-column prop="number" label="货品数量" width="299" />
            <el-table-column prop="url" label="规格图片" width="299">
              <template v-slot="scope">
                <img :src="scope.row.url" alt="" style=" height: 40px; width: 40px;"></img>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button size="mini" type="primary" @click="inventoryInstall(scope.row)">设置</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div class="dialogDiv">
      <el-dialog :title="title" :visible.sync="inventoryFormDialogFormVisible">
        <el-form ref="inventoryForm" :model="inventoryForm" :rules="rules" style="width: 400px;margin-left: 50px;">
          <el-form-item label="货品规格列" label-width="100px" prop="specifications">
            <el-tag>{{ inventoryForm.specifications[0] }}</el-tag>
          </el-form-item>
          <el-form-item label="货品售价" label-width="100px" prop="price">
            <el-input v-model="inventoryForm.price" style="width: 280px;" clearable />
          </el-form-item>
          <el-form-item label="货品数量" label-width="100px" prop="number">
            <el-input v-model="inventoryForm.number" style="width: 280px;" clearable />
          </el-form-item>
          <el-form-item label="货品图片" label-width="100px" prop="url">
            <el-upload class="avatar-uploader" :headers="headers"
              action="http://admin.bsmall.byesame.com/admin/storage/create" :show-file-list="false"
              :on-success="inventoryFormHandleAvata" :before-upload="beforeAvatarUpload">
              <img v-if="inventoryForm.url" :src="inventoryForm.url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="inventoryCancel">取 消</el-button>
          <el-button type="primary" @click="inventoryOK">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="crumbs">
      <div class="container">
        <h3>商品参数</h3>
        <el-button type="primary" @click="argumentAdd">添加</el-button>
        <div class="tables">
          <el-table :data="filteredAttributes" style="width: 100%">
            <el-table-column prop="attribute" label="商品参数名称" width="600" />
            <el-table-column prop="value" label="商品参数值" width="599" />
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button size="mini" type="primary" @click="argumentInstall(scope.row)">设置</el-button>
                <el-button size="mini" type="danger" @click="argumentDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div style="text-align: center;">
      <el-button @click="goList">取消</el-button>
      <el-button type="primary" @click="renewal">更新商品</el-button>
    </div>
    <div class="dialogDiv">
      <el-dialog :title="title" :visible.sync="argumentDialogFormVisible">
        <el-form ref="argumentForm" :model="argumentForm" :rules="rules" style="width: 400px;margin-left: 50px;">
          <el-form-item label="商品参数名称" label-width="100px" prop="price">
            <el-input v-model="argumentForm.attribute" style="width: 280px;" clearable />
          </el-form-item>
          <el-form-item label="商品参数值" label-width="100px" prop="number">
            <el-input v-model="argumentForm.value" style="width: 280px;" clearable />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="argumentCancel">取 消</el-button>
          <el-button type="primary" @click="argumentOK">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { detailGoods, listCatAndBrand, editGoods } from '@/api/goods'
import { getToken } from '@/utils/auth'
import Editor from '@tinymce/tinymce-vue'
export default {
  data() {
    return {
      valueTwo: [],
      query: {
        attributes: [],
        goods: {},
        products: [],
        specifications: []
      },
      categoryList: [],
      brandList: [],
      valueT: null,
      rules: {
        name: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ]
      },
      dialogImageUrl: '',
      tableData: [],
      tableDataProducts: [],
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      gelleryUrls: [],
      title: null,
      dialogFormVisible: false,
      ruleForm: {
        specification: null,
        value: null,
        picUrl: null
      },
      inventoryFormDialogFormVisible: false,
      inventoryForm: {
        specifications: [],
        price: null,
        number: null,
        url: null
      },
      argumentDialogFormVisible: false,
      argumentForm: {
        value: null,
        attribute: null
      },
      argumentId: null,
      argumentDeleId: null,
      editorInit: {
        language: 'zh_CN',
        height: 400,
        convert_urls: false,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: function (blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData).then(res => {
            success(res.data.data.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      },
    }
  },
  components:{Editor},
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    },
    filteredAttributes() {
      return this.query.attributes.filter(item => !item.deleted);
    }
  },
  created() {
    this.getList()
    this.getListCatAndBrand()
  },
  methods: {
    // 列表
    getList() {
      detailGoods(this.$route.query.id).then(res => {
        if (res.data.errno == 0) {
          this.query.goods = res.data.data.goods
          this.query.specifications = res.data.data.specifications
          this.query.products = res.data.data.products
          this.query.attributes = res.data.data.attributes
          this.dynamicTags = res.data.data.goods.keywords.split(',')
          this.query.goods.gallery = res.data.data.goods.gallery.map(url => ({ url }))
          this.galleryUrls = this.query.goods.gallery.map(item => item.url)
          if (this.query.goods.brandId == 0) {
            this.query.goods.brandId = ''
          }
        }
      })
    },
    // 所属分类
    getListCatAndBrand() {
      listCatAndBrand().then(res => {
        if (res.data.errno == 0) {
          this.categoryList = res.data.data.categoryList
          this.brandList = res.data.data.brandList
        }
      })
    },
    handleChange(value) {      
      if (Array.isArray(value) && value.length > 1) {
        this.query.goods.categoryId = value[1];
      } else {
        this.query.goods.categoryId = null; // 或者设置为其他默认值
      }
    },
    // 所选品牌
    handle(value) {
      this.query.goods.brandId = value
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.query.goods.picUrl = res.data.url
    },
    // 限制图片上传大小
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg'
      if (!isJPG) {
        this.$message.error('上传图片只能是jpeg/jpg/png/gif 格式!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M && isJPG
    },
    handleSuccess(res, fileList) {
      if (this.galleryUrls.length > 5) {
        // this.$message.error('最多上传5张图片')
        // return
        console.log(1111111111111)
      } else {
        this.galleryUrls.push(res.data.url)
      }
    },
    handleProgress() {},
    handleRemove(file, fileList) {
      if (file.response) {
        const urlToRemove = file.response.data.url
        const index = this.galleryUrls.indexOf(urlToRemove)
        if (index !== -1) {
          this.galleryUrls.splice(index, 1)
        }
      } else {
        const urlToRemove = file.url
        const index = this.galleryUrls.indexOf(urlToRemove)
        if (index !== -1) {
          this.galleryUrls.splice(index, 1)
        }
      }
    },
    // 关键字
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      this.query.goods.keywords = this.dynamicTags.join(',')
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.query.goods.keywords = this.dynamicTags.join(',')
      this.inputVisible = false
      this.inputValue = ''
    },
    // 更新商品
    renewal() {
      editGoods({
        attributes: this.query.attributes,
        goods: {
          ...this.query.goods,
          gallery: this.galleryUrls
        },
        products: this.query.products,
        specifications: this.query.specifications
      }).then(res => { 
        if (res.data.errno == 0) {
          this.$router.push({
            path: '/goods/list',
            query: {}
          })
          this.$notify({
            title: '成功',
            message: '编辑成功',
            type: 'success'
          });
        }
      }).catch(err => {
        this.$alert(`业务错误：${err.data.errmsg}`, '警告', {
            confirmButtonText: '确定',
            type: 'error'
          })
      })
    },
    // 取消
    goList() {
      this.$router.push({
        path: '/goods/list',
        query: {}
      })
    },
    // 商品规格上传图片
    handleAvata(res, file) {
      this.ruleForm.picUrl = res.data.url
    },
    // 商品规格设置
    install(row) {
      this.dialogFormVisible = true
      this.title = '设置规格'
      this.ruleForm.specification = row.specification
      this.ruleForm.value = row.value
      this.ruleForm.picUrl = row.picUrl
    },

    // 商品库存
    inventoryInstall(row) {
      this.inventoryFormDialogFormVisible = true
      this.inventoryForm.specifications = row.specifications
      this.inventoryForm.number = row.number
      this.inventoryForm.price = row.price
      this.inventoryForm.url = row.url
    },
    inventoryFormHandleAvata(res, file) {
      this.inventoryForm.url = res.data.url
    },

    // 校验
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.query.specifications[0].picUrl = this.ruleForm.picUrl
          this.query.specifications[0].value = this.ruleForm.value
          this.query.specifications[0].specification = this.ruleForm.specification
          this.query.specifications[0].updateTime = ''
          this.dialogFormVisible = false
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    // 商品库存的模态框确定/取消
    inventoryOK() {
      this.query.products[0].number = this.inventoryForm.number
      this.query.products[0].price = this.inventoryForm.price
      this.query.products[0].url = this.inventoryForm.url
      this.query.products[0].specifications = this.inventoryForm.specifications
      this.query.products[0].updateTime = ''
      this.inventoryFormDialogFormVisible = false
    },
    inventoryCancel() {
      this.inventoryFormDialogFormVisible = false
    },
    // 商品参数的模态框确定/取消
    argumentCancel() {
      this.argumentDialogFormVisible = false;
    },
    argumentOK() {
      if (this.title == "添加商品参数") {
        let demoArr = {
          attribute: this.argumentForm.attribute,
          value: this.argumentForm.value
        };
        this.query.attributes.unshift(demoArr);
        this.argumentDialogFormVisible = false;
      }else if (this.title == "编辑商品参数") {
        this.query.attributes.forEach(item => {
          if (item.id === this.argumentId) {
            item.attribute = this.argumentForm.attribute;
            item.value = this.argumentForm.value;
            item.updateTime = ''
          }
        });
        this.argumentDialogFormVisible = false;
      }
    },
    argumentAdd() {
      this.argumentDialogFormVisible = true;
      this.title = "添加商品参数";
      this.argumentForm.value = null;
      this.argumentForm.attribute = null;
    },
    // 商品参数设置
    argumentInstall(row) {
      if(row.id) {
        this.argumentDialogFormVisible = true;
        this.title = "编辑商品参数";
        this.argumentForm.attribute = row.attribute;
        this.argumentForm.value = row.value;
        this.argumentId = row.id;
      }else {
        this.argumentAdd()
      }
    },
    // 删除
    argumentDelete(row) {
      this.argumentDeleId = row.id;
      this.query.attributes.forEach(item => {
        if (item.id === this.argumentDeleId) {
          this.$set(item, 'deleted', true);
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">
.crumbs {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  margin-bottom: 10px;
  border-radius: 4px;
  border: 1px solid #e6ebf5;
  background-color: #fff;
  overflow: hidden;
  color: #303133;
  transition: .3s;
}

.container {
  padding: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 145px;
  height: 145px;
  line-height: 145px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}

::v-deep .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px !important;
  cursor: pointer !important;
  position: relative !important;
  overflow: hidden !important;
}

::v-deep .el-upload:hover {
  border-color: #409eff !important;
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

::v-deep .dialogDiv .el-form-item__label {
  text-align: left !important;
}
</style>
